package com.lawliet.example.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lawliet.example.model.system.SysRole;
import com.lawliet.example.model.system.SysRolePermission;
import com.lawliet.example.repository.system.SysRoleMapper;
import com.lawliet.example.repository.system.SysRolePermissionMapper;
import com.lawliet.example.service.system.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    /**
     * 分配权限
     * @param roleId 角色id
     * @param permissionIds 权限ids
     */
    @Override
    @Transactional
    public void assignPermission(Long roleId, String permissionIds) {
        //删除原先的权限
        LambdaQueryWrapper<SysRolePermission> deleteCon = new LambdaQueryWrapper<>();
        deleteCon.eq(SysRolePermission::getRoleId,roleId);
        sysRolePermissionMapper.delete(deleteCon);
        List<String> permissionIdList = Arrays.asList(permissionIds.split(","));
        for(String permissionId : permissionIdList){
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setRoleId(roleId);
            sysRolePermission.setPermissionId(Long.parseLong(permissionId));
            sysRolePermissionMapper.insert(sysRolePermission);
        }
    }
}
